from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from starlette.responses import JSONResponse
from starlette.middleware.cors import CORSMiddleware
import uvicorn
import logging

from price_analysis.api_v1 import router as router_v1
from price_analysis.core.config import settings

app = FastAPI()
app.include_router(router_v1, prefix=settings.api_v1_prefix)

logger = logging.getLogger("main")

fh = logging.FileHandler("app.log")
ch = logging.StreamHandler()

formatter = logging.Formatter(
    "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
fh.setFormatter(formatter)

logger.addHandler(ch)
logger.addHandler(fh)

logger.setLevel(logging.DEBUG)

logger_pocess = logger.getChild("processing-data")
logger_search = logger.getChild("search-online")

logger.info("Start logging")

# @app.exception_handler(RequestValidationError)
# async def validation_exception_handler(request: Request, exc: RequestValidationError):
#     return JSONResponse(
#         status_code=status.HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS,
#         content={
#             "result": False,
#             "error_type": status.HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS,
#             "error_message": exc.errors(),
#         },
#     )

app.add_middleware(
    CORSMiddleware,
    allow_origins="*",
    allow_credentials=True,
    allow_methods="*",
    allow_headers="*",
)

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
    )
